package com.rising.face.ali.bishi.threadprint5;


public class ThreadTest {

    //锁
    private static Object lock = new Object();
    static int threadSum = 10;

    private volatile static int currnet = 3;
    private volatile static int index = 0;
    private volatile static int[] arr = {3,3,8,2,0,1,9,8,3,5,8,3,0};

    public static void main(String[] args) {

        //总线程数
        ThreadPrint[] arr = new ThreadPrint[threadSum];
        // 创建线程
        for (int i = arr.length - 1; i >= 0; i--) {
            arr[i] = new ThreadPrint(i);
            arr[i].start();
        }
    }

    private static class ThreadPrint extends Thread {

        private int printNum;   //获取自己需要打印的数字

        ThreadPrint(int printNum) {
            this.printNum = printNum;
        }
        @Override
        public void run() {
            synchronized (lock) {
                while (index < arr.length) {
                    if (printNum == currnet) {
                        System.out.print(printNum);
                        index++;
                        if (index >= arr.length) {
                            return;
                        }
                        currnet = arr[index];
                        lock.notifyAll();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            //线程被打断
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}